import React, {useState,useMemo}from 'react'
import Child from './components/Child'

// useMemo: 优化性能
// useMemo(callback, [依赖项])
// 返回一个缓存的值，依赖项改变时重新执行 callback 计算结果, 依赖项没有改变直接从缓存中读取结果



const App = () => {
  const [title,setTitle] = useState('我是标题')

  const typeList = {
    0:'全部',
    1:'奇数',
    2:'偶数'
  }

  const [list,setList] = useState([])
  const [type,setType] = useState(0)

  const add = () => {
    childRef.current.add(10)
  }
  const curType = useMemo(() => {
    console.log('筛选')
    if(type === 1) {
      return list.filter(v => v.text % 2 === 1)
    }else if (type === 2) {
      return list.filter(v => v.text % 2 === 0)
    }else{
      return list
    }
  },[type,list])

  const childType = useMemo(() => {
    return <Child />
  },[])

  // const curTypeList = curType()
  return (
    <div>
      <h1>{title}</h1>
      <input type="text" value={title} onChange={e => setTitle(e.target.value)}/>
      <button onClick={add}>修改子元素的num</button>

      <hr />

      <button onClick={() => {
        let newType = type + 1 > 2? 0 : type + 1
        setType(newType)
      }}>{typeList[type]} {type}</button>

      <button onClick={() => {
        return setList([...list,{id:Date.now(), text:list.length}])
      }}>添加</button>
      <ul>
        {curType.map(v=><li key={v.id}>{v.text}</li>)}
      </ul>
      {childType}
    </div>

  )
}

export default App